package com.e3.web.index.client;

import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;

public class MainWorkspace extends LayoutContainer {

	private MainFrame mainFrame;
	
	private TabPanel tabPanel = new TabPanel();
	
	public MainWorkspace(MainFrame mainFrame){
		this.mainFrame = mainFrame;
	}

	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		this.setLayout(new FitLayout());
		
		this.add(tabPanel);
		
		String url = NavigatorHelper.getInfoCenterUrl();
		String title = NavigatorHelper.getInfoCenterTitle();
		openWorkspace(title, url, false);
	}
	
	public void openWorkspace(String title,String url){
		openWorkspace(title,url,true);	
	}
	
	public void openWorkspace(String title,String url,boolean enableClose){
		TabItem item = tabPanel.findItem(title, true);
		if(item==null){
			item = createTableItem(title);
			item.setUrl(url);
			item.setClosable(enableClose);
			tabPanel.add(item);
		}
		tabPanel.setSelection(item);		
	}
	
	public void openWorkspace(String title,Widget widget){
		TabItem item = tabPanel.findItem(title, true);
		if(item==null){
			item = createTableItem(title);
			item.add(widget);
			tabPanel.add(item);
		}
		tabPanel.setSelection(item);		
	}
	
	private TabItem createTableItem(String title){
		TabItem item = new TabItem();		
		item.setText(title);
		item.setClosable(true);
		item.setLayout(new FitLayout());
		
		item.addListener(Events.Select, new Listener<ComponentEvent>() {
			public void handleEvent(ComponentEvent be) {
				
				TabItem it = tabPanel.getSelectedItem();
				mainFrame.getStatusToolBar().setMessage(MainMessages.INSTANCE.module_info(it.getText()));
			}
		});
		mainFrame.getStatusToolBar().setMessage(MainMessages.INSTANCE.module_info(title));
		return item;
	}
}
